<template>
  <view>
    <tn-custom>
      <block slot="left">
        <view class='action border-custom text-white bp-top-home' :style="'width:' + Custom.width + 'px;margin-left:calc(750rpx - ' + Custom.right + 'px)'"
          @click="goBack">
          <text class='cuIcon-back'></text>
          <text class='cuIcon-homefill'></text>
        </view>
      </block>
    </tn-custom>

    <checkbox-group v-if="shoppingCartData.length > 0" @change="selectShoopingCartProduct">
      <view class="cu-card case">
        <view v-for="(product_item, product_index) in shoppingCartData" :key="product_index" class="cu-item shadow bg-red">
          <view class="image">
            <image :src="product_item.image" mode="aspectFill"></image>
            <view class="cu-tag bg-red" @click="deleteCartProduct(product_index)">删除</view>
            <view v-if="product_item.stock <= 0" class="cu-bar product-stock-shade">
              <text class="product-stock-title">缺货</text>
            </view>
            <view class="cu-bar" :class="[product_item.stock > 0 ? 'bg-shadeBottom' : '']">
              <text class="text-cut">{{ product_item.title }}</text>
              <text class="text-cut product-property">
                <text v-for="(product_property_item, product_property_index) in product_item.property" :key="product_property_index">
                  {{ product_property_index > 0 ? '; ' : '' }}{{ product_property_item }}
                </text>
              </text>
            </view>
          </view>

          <view class="flex padding-right justify-between">
            <view class="">
              <view class="cu-form-group">
                <checkbox
                  class='round blue'
                  :class="product_item.is_select ? 'checked' : ''"
                  :checked="product_item.is_select ? true : false"
                  :disabled="product_item.stock > 0 ? false : true"
                  :value="product_index"></checkbox>
                <view class="padding-right-xs"></view>
                <text class="text-gray">￥{{ product_item.price }}</text>
              </view>
            </view>
            <view class="margin-left margin-top text-gray text-lg">
              <goods-number-box
                bg-color="#e3e0e5"
                :min="product_item.stock > 0 ? 1 : 0"
                :value="product_item.count"
                :max="product_item.stock"
                @change="changeProductCount($event, product_index)"
               ></goods-number-box>
            </view>
          </view>
        </view>
      </view>
    </checkbox-group>
    
    <view v-else class="shopping-cart-empty">
      购物车为空
    </view>

    <view class="cu-tabbar-height"></view>

    <view class="cu-bar bg-white tabbar shop tn-footerfixed">
      <view class="action order-select-all">
        <view v-if="shoppingCartData.length > 0" class="cu-form-group">
          <checkbox-group @change="selectAllProduct">
            <checkbox
              class='round blue'
              :class="selectAllFlag?'checked':''"
              :checked="selectAllFlag"
              value="all"
             ></checkbox>
            <text class="padding-left-xs text-black">全选</text>
          </checkbox-group>
        </view>
      </view>
      <view class="padding-right">
        <text class="padding-right-xs">
          合计: <text class="text-red">¥ {{ productSumPrice }}</text>
        </text>
        <button class="cu-btn bg-red round shadow-blur order-btn" @click="navSubmitOrder">下单</button>
      </view>
    </view>

  </view>
</template>

<script>
  import GoodsNumberBox from '@/tn_shop/components/vk-u-number-box/vk-u-number-box.vue'
  import {
    getShoppingCartDataFromCache,
    updateShoppingCartDataToCache,
    addSubmitOrderProductToCache
  } from '@/utils/shop.js'
  import {
    getProductStockData
  } from '@/api/tn-shop.js'

  export default {
    name: 'TnShopShoppingCart',
    components: {
      GoodsNumberBox
    },
    data() {
      return {
        Custom: this.Custom,
        CustomBar: this.CustomBar,
        shoppingCartData: []
      };
    },
    computed: {
      productSumPrice: function() {
        return this.shoppingCartData.reduce((total, item) => {
          if (item.is_select) {
            return total + parseFloat(item.price) * parseInt(item.count)
          } else {
            return total
          }
        }, 0.00)
      },
      selectAllFlag: function() {
        if (this.shoppingCartData.length == 0) {
          return false
        }
        return this.shoppingCartData.every((item) => {
          if (item.stock > 0) {
            return item.is_select
          }
          return true
        })
      }
    },
    onLoad() {
      this._loadData()
    },
    methods: {

      // 这中某一个商品
      selectShoopingCartProduct(event) {
        const {
          detail: { value }
        } = event
        // console.log(value);
        
        // 遍历购物车数据数组，如果所选下标存在以选择数组中则设置为true，否则为false
        this.shoppingCartData.map((item, index) => {
          // console.log(value, index);
          if (value.includes((index).toString())) {
            this.shoppingCartData[index].is_select = true
          } else {
            this.shoppingCartData[index].is_select = false
          }
        })
        // console.log(this.shoppingCartData)
        
        // 检查是否为已经全选
        // this._checkIsSelectAll()
        
        // 更新数据到缓存中
        updateShoppingCartDataToCache(this.shoppingCartData)
      },
      
      // 删除某一个商品
      deleteCartProduct(index) {
        this.shoppingCartData.splice(index, 1)
        
        // this._checkIsSelectAll()
        
        // 更新数据到缓存中
        updateShoppingCartDataToCache(this.shoppingCartData)
      },
      
      // 更改商品的数量信息
      changeProductCount(event, index) {
        const { value } = event
        // console.log(value, index);
        this.shoppingCartData[index].count = value
        
        // 更新数据到缓存中
        updateShoppingCartDataToCache(this.shoppingCartData)
      },
      // 点击全选按钮
      selectAllProduct(event) {
        const {
          detail: { value }
        } = event
        // console.log(value);
        
        if (value.includes('all')) {
          // 设置购物车里面的商品为全部选择
          this.shoppingCartData.forEach((item, index) => {
            if (item.stock > 0) {
              this.shoppingCartData[index].is_select = true
            }
          })
        } else {
          // 设置购物车里面的商品为全部不选择
          this.shoppingCartData.forEach((item, index) => {
            this.shoppingCartData[index].is_select = false
          })
        }
        
        // 更新数据到缓存中
        updateShoppingCartDataToCache(this.shoppingCartData)
      },
      
      // 跳转到下单页面
      navSubmitOrder() {
        // 取出已经选择的商品
        const select_product = this.shoppingCartData.filter((item) => {
          return item.stock > 0 && item.is_select
        })
        // console.log(select_product);
        
        if (select_product.length == 0) {
          uni.showToast({
            icon: 'none',
            title: '请选择商品'
          })
          return 
        }
        
        addSubmitOrderProductToCache(select_product)
        uni.navigateTo({
          url: '/tn_shop/submit_order/submit_order?from=cart'
        })
        
      },
      
      // 判断是跳转到首页还是上一页
      goBack() {
        if (this.from == 'share') {
          uni.navigateTo({
            url: '/pages/index/index'
          })
        } else {
          uni.navigateBack({
            delta: 1
          })
        }
      },

      // 加载默认数据
      _loadData() {
        this._getShoppingCartData()
      },
      
      // 检查是否已经为全选
      _checkIsSelectAll() {
        if (this.shoppingCartData.length == 0) {
          this.selectAllFlag = false
          return
        }
        this.selectAllFlag = this.shoppingCartData.every((item) => {
          if (item.stock > 0) {
            return item.is_select
          }
          return true
        })
        console.log(this.shoppingCartData, this.selectAllFlag);
      },

      // 从缓存中获取购物车数据
      _getShoppingCartData() {
        this.shoppingCartData = getShoppingCartDataFromCache()
        if (this.shoppingCartData && this.shoppingCartData.length > 0) {
          this._updateProductStockData()
        }
      },
      
      // 更新购物车里商品的库存信息
      _updateProductStockData() {
        // 获取购物车里面商品的给规格id
        let specs_ids = this.shoppingCartData.reduce((total, item) => {
          return total.concat(item.id)
        }, [])
        // 将数组转换为字符串，每个元素用，隔开
        specs_ids = specs_ids.join(',')
        // console.log(specs_ids);
        getProductStockData({
          specs_id: specs_ids
        }).then((response) => {
          const { data } = response
          
          for (var i = 0; i < this.shoppingCartData.length; i++) {
            const item = this.shoppingCartData[i]
            const stock = data[item.id]
            if (stock == undefined) {
              // 当前商品已经下架了，则从数组中删除
              this.shoppingCartData.splice(i, 1)
            } else {
              this.shoppingCartData[index].stock = stock
              this.shoppingCartData[index].is_select = (stock > 0 && item.is_select) ? true : false
              // 判断库存是否比现在加入的商品数量少
              if (stock > 0) {
                if (item.count > stock) {
                  this.shoppingCartData[index].count = stock
                }
                if (this.shoppingCartData[index].count == 0) {
                  this.shoppingCartData[index].count = 1
                }
              } else {
                this.shoppingCartData[index].count = 0
              }
            }
          }
          
          // this.shoppingCartData.forEach((item, index) => {
          //   const stock = data[item.id]
          //   console.log(data, stock);
          //   this.shoppingCartData[index].stock = stock
          //   this.shoppingCartData[index].is_select = (stock > 0 && item.is_select) ? true : false
          //   // 判断库存是否比现在加入的商品数量少
          //   if (stock > 0) {
          //     if (item.count > stock) {
          //       this.shoppingCartData[index].count = stock
          //     }
          //     if (this.shoppingCartData[index].count == 0) {
          //       this.shoppingCartData[index].count = 1
          //     }
          //   } else {
          //     this.shoppingCartData[index].count = 0
          //   }
          // })
          // 更新数据到缓存中
          updateShoppingCartDataToCache(this.shoppingCartData)
          // this._checkIsSelectAll()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .order-select-all {
    width: 100px !important;
  }

  .order-btn {
    width: 100px;
  }
  
  .product-property {
    width: 125px;
    text-overflow: clip;
  }
  
  .shopping-cart-empty {
    width: 100%;
    text-align: center;
    margin: auto;
  }
  
  .product-stock-shade {
    background-image: -webkit-linear-gradient(rgba(103, 103, 103, 0.71), rgba(255, 255, 255, 0.73));
    background-image: linear-gradient(rgba(103, 103, 103, 0.71), rgba(255, 255, 255, 0.73));
    color: #ff0000;
    height: 100%;
  }
  .product-stock-title {
    text-align: center;
    margin: auto;
    font-size: 25px;
  }
</style>
